package com.PictureSite.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.PictureSite.DatabaseAccess.PictureSiteCreatePostDAO;
import com.PictureSite.model.PictureSitePostModel;
import com.PictureSite.model.UserPost;
import com.PictureSite.model.Voter;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.files.FileService;
import org.apache.commons.lang.StringUtils;

public class PictureSiteHomeController extends PictureSiteController {
	
	private final FileService fileService;
	
	private PictureSiteCreatePostDAO dataStore;
	
	public PictureSiteHomeController(final FileService fileService, final PictureSiteCreatePostDAO dataStore) {
		this.fileService = fileService;
		this.dataStore = dataStore;
	}
	
	public void filldata(PictureSitePostModel model,HttpServletRequest req, HttpServletResponse resp) throws Exception {

		List<UserPost> userPosts = new ArrayList<UserPost>();
		List<Entity> tempList = dataStore.getPostByDateDesc(model.getPageLimit(),model.getPageNum());
		String ip = req.getRemoteAddr().toString();
		
		if (tempList.isEmpty()) {
			throw new Exception("Page out of bounds");
		}
		model.setLastPage(dataStore.isLastImagePage(model.getPageLimit(),model.getPageNum()));
		
		for (Entity row : tempList) {
			UserPost userPost = new UserPost();
			userPost.setTitle(row.getProperty("title").toString());
			userPost.setUserName(row.getProperty("userName").toString());
			userPost.setDatePosted(row.getProperty("date").toString());
			userPost.setBlobId(row.getProperty("blobId").toString());
			userPost.setVotes(Integer.parseInt(row.getProperty("likes").toString()));
			userPost.setId(String.valueOf(row.getKey().getId()));
			userPost.setVoteType(dataStore.getVoters(userPost.getId(),ip));
			userPosts.add(userPost);
		}
		model.setUserPosts(userPosts);
		
		getTopPosts(model,dataStore);
	}

	public int getPageNum(HttpServletRequest req) throws IOException {
		//Need to remake and have servlet based parameter extraction.
		if (!StringUtils.isEmpty(req.getPathInfo())) {
			String pageNumberStr = req.getPathInfo().replace("/", "");
			if (!StringUtils.isEmpty(pageNumberStr)) {
				int pageNumber = Integer.parseInt(pageNumberStr);
				return pageNumber;
			}
		}
		return 1;
	}
	
	private void countVotes(String ip, String id, String type,Voter voter, UserPost userPost) throws Exception{
		voter.setIp(ip);
		voter.setPostId(id);
		//if the user hasn't voted allow them to vote.
		if(dataStore.getIpsForUserPost(id) == null || !dataStore.getIpsForUserPost(id).contains(ip)) {
			if (type.equals("up")) {
				userPost.setVoteType(true);
				voter.setUpVote(true);
				userPost.upvote();
			} else if (type.equals("down")) {
				userPost.setVoteType(false);
				voter.setUpVote(false);
				userPost.downvote();
			}
			dataStore.storeVotes(userPost,voter);
		} else {
			if (dataStore.getVoteType(id) == false && type.equals("up")) {
				userPost.setVoteType(true);
				voter.setUpVote(true);
				userPost.upvote();
				userPost.upvote();
			} else if (dataStore.getVoteType(id) == true && type.equals("down")) {
				userPost.setVoteType(false);
				voter.setUpVote(false);
				userPost.downvote();
				userPost.downvote();
			}
			dataStore.changeVote(userPost,voter,type);
		}
	}
	
	public void handleVotes(PictureSitePostModel model, HttpServletRequest req) throws Exception {
		String type = req.getParameter("type");
		String ip = req.getRemoteAddr().toString();
		String id = req.getParameter("id").toString();
		Voter voter = new Voter();
		
		if (model.getUserPosts() == null) {
			UserPost userPost = new UserPost();
			countVotes(ip,id,type,voter,userPost);
		} else {
			for(UserPost userPost : model.getUserPosts()) {
				//find the post that relates to the button selected
				if (userPost.getId().equals(id)) {
					countVotes(ip,id,type,voter,userPost);
				}
			}
		}
	}
}
